package com.dyrnq.seckill.service.impl;

import com.dyrnq.seckill.entity.SeckillGoods;
import com.dyrnq.seckill.mapper.OrderInfoMapper;
import com.dyrnq.seckill.mapper.SeckillGoodsMapper;
import com.dyrnq.seckill.mapper.SeckillOrderMapper;
import com.dyrnq.seckill.service.CleanDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CleanDataServiceImpl implements CleanDataService {

    public static final String SECKILL_STOCK_KEY = "seckill:stock:";
    public static final String SECKILL_ORDER_KEY = "seckill:order:";
    private final SeckillGoodsMapper seckillGoodsMapper;
    private final SeckillOrderMapper seckillOrderMapper;
    private final OrderInfoMapper orderInfoMapper;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    @Transactional
    public void clean() {
        orderInfoMapper.delete(null);
        seckillOrderMapper.delete(null);

        List<SeckillGoods> list = seckillGoodsMapper.selectList(null);

        for (SeckillGoods seckillGoods : list) {
            seckillGoods.setStockCount(100);
            seckillGoodsMapper.updateById(seckillGoods);
            stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + seckillGoods.getId(), seckillGoods.getStockCount().toString());
            stringRedisTemplate.delete(SECKILL_ORDER_KEY + seckillGoods.getId());
        }

    }
}
